package cmd

import (
	"gitee.com/feimos/dm/core"
	"gitee.com/feimos/dm/utils"
	"github.com/urfave/cli/v2"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

// InitCommand 处理 init subcommand
func InitCommand(c *cli.Context) error {

	root := c.Args().First()

	debug := c.Bool("debug")

	noRun := c.Bool("no-run")

	if len(root) == 0 {
		envRoot, err := filepath.Abs(filepath.Dir(os.Args[0]))

		if err != nil {
			return err
		}

		root = envRoot
	}

	ignoreList := core.LoadIgnoreFile(root, true)

	if noRun {
		dmFile := utils.JoinPath(root, core.DmFile)
		log.Printf("stop running document retrieval")
		return ioutil.WriteFile(dmFile, []byte(""), 0644)
	}

	fileMaps, err := core.ScanRoot(root, ignoreList, debug)

	if err != nil {
		return err
	}

	err = utils.RemoveAllEmptyDir(root, ignoreList, false)

	if err != nil {
		return err
	}

	document, err := core.BuildYaml(root, fileMaps)

	if err != nil {
		return err
	}

	err = utils.RemoveAllEmptyDir(root, ignoreList, true)

	if err != nil {
		return err
	}

	err = core.WriteYaml(document, false)

	if err != nil {
		return err
	}

	return nil
}
